package com.example.homework5;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

    Button login_btn;
    EditText account, password;

    private static final String PREFS_NAME = "User_Data";
    private static final String Last_account = "last_account";
    private static final String Last_password = "last_password";
    private SharedPreferences user_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        user_data = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

        login_btn = findViewById(R.id.login_btn);
        account = findViewById(R.id.account);
        password = findViewById(R.id.password);

        String has_save_account = user_data.getString(Last_account, "");
        String has_save_password = user_data.getString(Last_password, "");

        if (!has_save_account.isEmpty() && !has_save_password.isEmpty()) {
            account.setText(has_save_account);
            password.setText(has_save_password);
        }

        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (account.getText().toString().isEmpty() || password.getText().toString().isEmpty()) {
                    Toast.makeText(MainActivity.this, "请输入账号和密码", Toast.LENGTH_SHORT).show();
                }
                else {
                    if (user_data.getString(account.getText().toString(), "").isEmpty()) {
                        user_data.edit().putString(account.getText().toString(), password.getText().toString()).apply();
                        Toast.makeText(MainActivity.this, "这是新账号", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        if (password.getText().toString().equals(user_data.getString(account.getText().toString(), ""))) {
                            Toast.makeText(MainActivity.this, "这个已存在", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            Toast.makeText(MainActivity.this, "密码不正确", Toast.LENGTH_SHORT).show();
                        }
                    }
                    user_data.edit().putString("last_account", account.getText().toString()).apply();
                    user_data.edit().putString("last_password", password.getText().toString()).apply();
                }
            }
        });
    }
}